﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.SessionState;
using DAL;
using System.Configuration;

namespace AjaxLibrary
{
    class customer : IHttpHandler, IRequiresSessionState
    {
        #region IHttpHandler 成员

        bool IHttpHandler.IsReusable
        {
            get { return true; }
        }

        void IHttpHandler.ProcessRequest(HttpContext context)
        {
            string param = context.Request.QueryString["Param"];

            switch (param.ToLower())
            {
                case "checkvemailformat":
                    string emailStr = "0";
                    string email = context.Request.QueryString["email"];

                    if (Library.Email.IsEmailAddress(email))
                        emailStr = "1";

                    context.Response.Output.Write(emailStr);

                    break;
                case "isexistuser":
                    string username = context.Request.QueryString["username"];
                    if (Library.Email.IsEmailAddress(username))
                    {
                        if (logic.customer.isExistUser(username))
                            context.Response.Output.Write("1");
                        else
                            context.Response.Output.Write("0");
                    }
                    else
                    {
                        context.Response.Output.Write("2");
                    }
                    return;
                case "login":
                    LoginFacade(context.Request, context.Response);
                    return;
                case "checksession":
                    if (logic.customer.userId == 0)
                    {
                        context.Response.Output.Write("0");
                    }
                    else
                    {
                        context.Response.Output.Write("1");
                    }
                    return;
                case "checkinfo":

                default:
                    context.Response.Output.Write("Unknow request URL");
                    return;
            }
        }

        private void LoginFacade(HttpRequest request, HttpResponse response)
        {
            response.ContentType = "text/json";

            int EMPTY_USERNAME = 5;// 用户名为空
            int EMPTY_PASSWORD = 6;// 密码为空
            int EMPTY_IDEN_COD = 7;// 验证码为空
            /*int USERNAME_NOT_EXIST = 8;// 用户名不存在
            int PASSWORD_WRONG = 9;// 密码错误
            int USER_EXPIRE = 10;// 用户已过期
            int USER_REFUSE = 11;// 用户已被禁用*/
            int LOGIN_SUCCESS = 12;// 登录成功
            int FORCE_CHANGE_PASSOWRD = 13;// 强制弱密码用户修改密码

            if (string.IsNullOrEmpty(request.Form["txtUserName"]))
            {
                response.Output.Write("{\"DiyStatusCode\":" + EMPTY_USERNAME + "}");
                return;
            }
            if (string.IsNullOrEmpty(request.Form["txtPassword"]))
            {
                response.Output.Write("{\"DiyStatusCode\":" + EMPTY_PASSWORD + "}");
                return;
            }
            if (string.IsNullOrEmpty(request.Form["txtValidateCode"]))
            {
                response.Output.Write("{\"DiyStatusCode\":" + EMPTY_IDEN_COD + "}");
                return;
            }

            string userName = request.Form["txtUserName"];
            string passWord = request.Form["txtPassword"];
            string validateCode = request.Form["txtValidateCode"];
            bool rememberMe = Convert.ToBoolean(request.Form["chkRememberMe"]);

            // 验证码校验
            int validateCodeResult = ValidateCode(request, validateCode);
            if (validateCodeResult != 4)
            {
                response.Output.Write("{\"DiyStatusCode\":" + validateCodeResult + "}");
                return;
            }

            DAL.CustomerEntity cusomter = logic.customer.login(userName, Library.StringLbl.EncryptMD5(passWord));

            // 登录成功
            if (cusomter.StatusCode == 12 && cusomter.CustomerId != 0 && !string.IsNullOrEmpty(cusomter.CompanyType) && cusomter.CompanyId != 0)
            {
                // 用户信息存储
                logic.customer.RecordLogin(cusomter.CustomerId, cusomter.CompanyId, rememberMe);
                logic.loginLog.insertFade(cusomter.CustomerId, "2", HttpContext.Current.Session.SessionID);

                // 密码规则调整（根据配置指定所有供应商和采购商）
                if (ConfigurationManager.AppSettings["ForceChangePasswordFilter"] == cusomter.CompanyType || ConfigurationManager.AppSettings["ForceChangePasswordFilter"] == "3")
                {
                    if (passWord == ConfigurationManager.AppSettings["InitPassword"])
                    {
                        string passwordCUrl = string.Format("firstpwdEdit.html?customid={0}", ToBase64(Library.StringLbl.EncryptRc2(cusomter.CustomerId.ToString())));
                        response.Output.Write("{\"DiyStatusCode\":" + FORCE_CHANGE_PASSOWRD + ",\"Url\":\"" + passwordCUrl + "\"}");
                        return;
                    }
                }

                // 登录成功跳转页面
                response.Output.Write("{\"DiyStatusCode\":" + LOGIN_SUCCESS + "}");
                return;
            }
            else
            {
                response.Output.Write("{\"DiyStatusCode\":" + cusomter.StatusCode + "}");
                return;
            }
        }

        // 验证码效验
        private int ValidateCode(HttpRequest request, string validateCode)
        {
            int IDEN_CODE_EXPIRE = 1;// 验证码过期
            int BROWSER_SUPPORT_COOKIE = 2;// 浏览器不支持Cookie
            int ERROR_IDEN_CODE = 3;// 验证码错误
            int IDEN_CODE_PASS = 4;// 验证码通过

            if (request.Browser.Cookies)
            {
                if (request.Cookies["CheckCode"] == null)
                {
                    return IDEN_CODE_EXPIRE;
                }
                else
                {
                    if (String.Compare(request.Cookies["CheckCode"].Value, validateCode, true) != 0)
                    {
                        return ERROR_IDEN_CODE;
                    }
                    else
                    {
                        return IDEN_CODE_PASS;
                    }
                }
            }
            else
            {
                return BROWSER_SUPPORT_COOKIE;
            }
        }

        private string ToBase64(string source)
        {
            byte[] bytes_1 = System.Text.Encoding.Default.GetBytes(source);
            return Convert.ToBase64String(bytes_1);
        }

        #endregion
    }
}
